package com.samphanie.auiu.admin.service.impl;

import cn.hutool.json.JSONUtil;
import com.samphanie.auiu.admin.domain.vo.AdminVo;
import com.samphanie.auiu.admin.feign.IAuiuAuthService;
import com.samphanie.auiu.admin.service.IAdminUserService;
import com.samphanie.auiu.common.dto.AdminLoginDto;
import com.samphanie.auiu.common.dto.UserProfileDto;
import com.samphanie.auiu.common.utils.ApiResponse;
import feign.Response;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author ZSY
 * @email 1451691457@qq.com
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminUserServiceImpl implements IAdminUserService {

    private final IAuiuAuthService authService;

    @Override
    public void getImageCode(HttpServletResponse servletResponse) {
        Response response = authService.getImageCode();
        Response.Body body = response.body();
        InputStream fileInputStream = null;
        OutputStream outStream;
        try {
            fileInputStream = body.asInputStream();
            outStream = servletResponse.getOutputStream();

            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes)) != -1) {
                outStream.write(bytes, 0, len);
            }
            fileInputStream.close();
            outStream.close();
            outStream.flush();
        } catch (Exception ignored) {

        }
    }

    @Override
    public ApiResponse<?> adminLogin(AdminLoginDto loginDto) {
        return authService.adminLogin(loginDto);
    }

    @Override
    public ApiResponse<?> getCurrentAdminUser() {
        ApiResponse<?> profile = authService.getProfile();
        if (profile.getCode() == 200) {
            Object data = profile.getData();
            val jsonObject = JSONUtil.parseObj(data);
            val userProfileDto = JSONUtil.toBean(jsonObject, UserProfileDto.class);
            val info = AdminVo.fromUser.apply(userProfileDto);
            return ApiResponse.success(info);
        }
        return ApiResponse.failed();
    }

}
